package rmi.write;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TcpHander {

	private Integer port;
	private Object service;
	private ExecutorService service2 = Executors.newCachedThreadPool();
    
	
	public TcpHander(Integer port, Object service) {
		super();
		this.port = port;
		this.service = service;
	}


	public void publisher() {
		try {
			ServerSocket serverSocket = new ServerSocket(port);
			while(true) {
				Socket socket=serverSocket.accept();
				service2.execute(new socketHandler(socket,service) );
			}
		} catch (Exception e) {
			throw new RuntimeException("发布失败");
           
		}

	}
	
	

}


class socketHandler implements Runnable{
	
	private Socket socket;
	private Object service;

	public socketHandler(Socket socket,Object service) {
		super();
		this.socket = socket;
		this.service=service;
	}



	@Override
	public void run() {
		ObjectInputStream inputStream =null;
		ObjectOutputStream objectOutputStream=null;
		try {
			 inputStream = new ObjectInputStream(socket.getInputStream());
			 RpcRequest readObject = (RpcRequest) inputStream.readObject();
			 Object handler = handler(readObject);
			 objectOutputStream=new ObjectOutputStream(socket.getOutputStream());
			 objectOutputStream.writeObject(handler);
			 objectOutputStream.flush();
		
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(objectOutputStream!=null) {
				try {
					objectOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if (inputStream!=null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		
	}
	
	private Object handler(RpcRequest request) {
		try {
			String className = request.getClassName();
			String methodName=request.getMethodName();
			Object[] params = request.getParams();
			Class[] parameterTypes=new Class[params.length];
			for (int i = 0; i < params.length; i++) {
				parameterTypes[i]=params[i].getClass();
			}
			Method method = service.getClass().getMethod(methodName, parameterTypes);
			return method.invoke(service, params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
